﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Linq;

namespace AnythingTheyCanDo.LinqToDom
{
    public class jQueryInterface
    {

    }
    public class jQuery
    {
        private ScriptObject jQueryResults;
        private DomNode[] nodes;
        private string[] resultIds;
        public jQuery(string queryString)
        {
            jQueryResults = (ScriptObject) HtmlPage.Window.Invoke("jQueryExec", queryString);
            resultIds = jQueryResults.ConvertTo<string[]>();
            populateNodes();

        }

        public DomNode[] Nodes
        {
            get { return nodes; }
        }

        private void populateNodes()
        {
            if (resultIds == null)
                return;
            if (resultIds.Length > 0)
            {
                var htmlElements = from id in resultIds
                                   select HtmlPage.Document.GetElementById(id);
                List<DomNode> tempNodes = new List<DomNode>();
                foreach (HtmlElement element in htmlElements)
                {
                    switch (element.TagName)
                    {
                        case "div":
                            tempNodes.Add(new Div(element));
                            break;
                        case "span":
                            tempNodes.Add(new Span(element));
                            break;
                        case "a":
                            tempNodes.Add(new Anchor(element));
                            break;
                        default:
                            tempNodes.Add(new DomNode(element));
                            break;
                    }
                }
                nodes = tempNodes.ToArray();
                tempNodes.Clear();
            }
        }
    }
}